<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      http://www.dbshop.net/
 * @copyright Copyright (c) 2012-2016 DBShop.net Inc. (http://www.dbshop.net)
 * @license   http://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风
 *
 */

namespace Dbapi\Controller;

use Admin\Controller\BaseController;
use Admin\Service\DbshopOpcache;
use Zend\Config\Reader\Ini;
use Zend\Config\Writer\PhpArray;

class IndexController extends BaseController
{
    /**
     * apiKey设置
     */
    public function indexAction ()
    {
        $array = array();

        if($this->request->isPost()) {
            $apiArray = $this->request->getPost()->toArray();
            if(isset($apiArray['dbshop_api_key'])) {
                $apiConfig = array(
                    'apiKey'            => $apiArray['dbshop_api_key'],
                    'dbshopApiState'  => $apiArray['dbshop_api_state']
                );
                $phpWriter = new PhpArray();
                $phpWriter->toFile(DBSHOP_PATH . '/module/Extendapp/Dbapi/data/apiKey.php', $apiConfig);
                DbshopOpcache::invalidate(DBSHOP_PATH . '/module/Extendapp/Dbapi/data/apiKey.php');
                $array['success_msg'] = $this->getDbshopLang()->translate('API 密钥设置成功！');
            }
        }

        $array['api'] = array();
        if(file_exists(DBSHOP_PATH . '/module/Extendapp/Dbapi/data/apiKey.php')) $array['api'] = include DBSHOP_PATH . '/module/Extendapp/Dbapi/data/apiKey.php';

        return $array;
    }
    /**
     * 生成api密钥
     */
    public function ajaxCreateKeyAction()
    {
        $httpHost   = $_SERVER['HTTP_HOST'];
        $chars      = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
        $str        = $httpHost . $chars[rand(0, 25)] . str_replace('.', '',microtime(true));
        $apiKey     = md5($str);
        exit($apiKey);
    }
    /**
     * 广告设置列表
     * @return array
     */
    public function adIndexAction()
    {
        $array = array();

        $array['ad'] = $this->appIni('ad');

        $adArray = $this->getDbshopTable('ApiSetAdTable')->listAd();
        if(is_array($adArray) and !empty($adArray)) {
            foreach($adArray as $adValue) {
                $array['ad_array'][$adValue['dbapi_ad_code']] = $adValue;
            }
        }

        return $array;
    }
    /**
     * 设置广告
     * @return array
     */
    public function adEditAction()
    {
        $code = $apiArray = $this->request->getQuery('code');
        if(empty($code)) return $this->redirect()->toRoute('dbapi/default', array('action'=>'adIndex'));

        $array['ad'] = $this->appIni('ad', $code);

        //添加或编辑广告
        if($this->request->isPost()) {
            $adArray = $this->request->getPost()->toArray();
            if(!in_array($adArray['dbapi_ad_type'], array('image','slide'))) {
                $adArray['dbapi_ad_body'] = $adArray['ad_' . $adArray['dbapi_ad_type']];
            }
            //广告基础内容插入
            if(empty($adArray['dbapi_ad_id']))  $adId = $this->getDbshopTable('ApiSetAdTable')->addAd($adArray);
            else $adId = $adArray['dbapi_ad_id'];

            //图片广告处理
            if($adArray['dbapi_ad_type'] == 'image') {
                $adImage = $this->getServiceLocator()->get('shop_other_upload')->adImageUpload('ad_image', (isset($adArray['old_ad_image']) ? $adArray['old_ad_image'] : ''), '', '', 'api');
                if($adImage['image'] != '')$this->getDbshopTable('ApiSetAdTable')->updateAd(array('dbapi_ad_body'=>$adImage['image']), array('dbapi_ad_id'=>$adId));
            }
            //广告基础内容编辑（当为编辑状态时）
            if($adArray['dbapi_ad_id'] > 0) $this->getDbshopTable('ApiSetAdTable')->updateAd($adArray, array('dbapi_ad_id'=>$adId));

            //幻灯片广告处理
            if($adArray['dbapi_ad_type'] == 'slide') {
                //当为编辑状态时
                if($adArray['dbapi_ad_id'] > 0) $this->getDbshopTable('ApiSetAdSlideTable')->delSlideData(array('dbapi_ad_id'=>$adId));

                for($i=1; $i<=5; $i++) {
                    if($_FILES['ad_slide_image_' . $i]['name'] != '' or (isset($adArray['old_ad_slide_image_' . $i]) and $adArray['old_ad_slide_image_' . $i] != '')) {
                        $slideArray = array();
                        $slideImage = $this->getServiceLocator()->get('shop_other_upload')->adImageUpload('ad_slide_image_' . $i, (isset($adArray['old_ad_slide_image_' . $i]) ? $adArray['old_ad_slide_image_' . $i] : ''), '', '', 'api');

                        $slideArray['dbapi_ad_id']          = $adId;
                        $slideArray['dbapi_ad_slide_info']  = $adArray['ad_slide_text_' . $i];
                        $slideArray['dbapi_ad_slide_image'] = $slideImage['image'];
                        $slideArray['dbapi_ad_slide_sort']  = $adArray['ad_slide_sort_' . $i];
                        $slideArray['dbapi_ad_slide_url']   = $adArray['ad_slide_url_' . $i];
                        $this->getDbshopTable('ApiSetAdSlideTable')->addAdSlide($slideArray);
                    }
                }
                unset($slideArray, $slideImage);
            }
            //记录操作日志
            $this->insertOperlog(array('operlog_name'=>$this->getDbshopLang()->translate('API广告设置'), 'operlog_info'=>$this->getDbshopLang()->translate('设置广告') . '&nbsp;' . $array['ad']['name']));

            unset($adArray);
            return $this->redirect()->toRoute('dbapi/default', array('action'=>'adIndex'));
        }

        $adInfo = $this->getDbshopTable('ApiSetAdTable')->infoAd(array('dbapi_ad_code'=>$code));
        if(is_array($adInfo) and !empty($adInfo)) {
            $array['ad'] = array_merge($array['ad'], $adInfo);

            if($adInfo['dbapi_ad_type'] == 'slide') {
                $array['slide_array'] = $this->getDbshopTable('ApiSetAdSlideTable')->listAdSlide(array('dbapi_ad_id'=>$adInfo['dbapi_ad_id']));
            }
        }

        return $array;
    }
    /**
     * 清除广告
     * @return array
     */
    public function adClearAction()
    {
        $delState= $this->getDbshopLang()->translate('API广告清除失败！');
        $adId    = $this->request->getPost('ad_id');    //广告id

        $adInfo  = $this->getDbshopTable('ApiSetAdTable')->infoAd(array('dbapi_ad_id'=>$adId));
        if(!empty($adInfo)) {
            if($adInfo['dbapi_ad_type'] == 'image' and $adInfo['dbapi_ad_body'] != '') {
                @unlink(DBSHOP_PATH . $adInfo['dbapi_ad_body']);
            }
            if($adInfo['dbapi_ad_type'] == 'slide') $this->getDbshopTable('ApiSetAdSlideTable')->delAdSlide(array('dbapi_ad_id'=>$adId));
            $this->getDbshopTable('ApiSetAdTable')->delAd(array('dbapi_ad_id'=>$adId));
            //记录操作日志
            $ad = $this->appIni('ad', $adInfo['dbapi_ad_code']);
            $this->insertOperlog(array('operlog_name'=>$this->getDbshopLang()->translate('API广告设置'), 'operlog_info'=>$this->getDbshopLang()->translate('清除广告') . '&nbsp;' . $ad['name']));
            $delState = 'true';
        }
        exit($delState);
    }
    /**
     *
     */
    public function delSlideImageAction()
    {
        $delState   = 'false';
        $adId       = (int) $this->request->getPost('ad_id');    //广告id
        $slideImage = $this->request->getPost('image_path');

        if($adId > 0 and !empty($slideImage)) {
            $where = array('dbapi_ad_id'=>$adId, 'dbapi_ad_slide_image'=>$slideImage);
            $slideInfo = $this->getDbshopTable('ApiSetAdSlideTable')->infoAdSlide($where);
            if(isset($slideInfo->dbapi_ad_id) and $slideInfo->dbapi_ad_id > 0) {
                if($slideInfo->dbapi_ad_slide_image != '') @unlink(DBSHOP_PATH . $slideInfo->dbapi_ad_slide_image);
                $this->getDbshopTable('ApiSetAdSlideTable')->delSlideData($where);
                $delState = md5($slideImage);
            }
        }
        exit($delState);
    }
    /**
     * 商品设置列表
     * @return array
     */
    public function goodsIndexAction()
    {
        $array = array();

        $array['goods'] = $this->appIni('goods');

        $goodsGroup = $this->getDbshopTable('ApiSetGoodsTable')->listApiGoodsGroup(array());
        if(is_array($goodsGroup) and !empty($goodsGroup)) {
            foreach($goodsGroup as $goodsValue) {
                $array['goods_group'][$goodsValue['dbapi_goods_code']] = $goodsValue;
            }
        }

        return $array;
    }
    /**
     * 设置商品
     * @return array
     */
    public function goodsEditAction()
    {
        $code = $this->request->getQuery('code');
        if(empty($code)) return $this->redirect()->toRoute('dbapi/default', array('action'=>'goodsIndex'));

        $array['goods'] = $this->appIni('goods', $code);

        $array['goods_list'] = $this->getDbshopTable('ApiGoodsTable')->goodsListPage(array('limit'=>100, 'order'=>'goods_api.dbapi_goods_sort ASC','where'=>array('goods_api.dbapi_goods_code'=>$code), 'inner'=>array('dbshop_dbapi_goods'=>true)));

        return $array;
    }
    /**
     * 添加API商品
     */
    public function addApiGoodsAction()
    {
        $goodsCode = trim($this->request->getPost('goods_code'));
        $goodsId   = intval($this->request->getPost('goods_id'));
        if($goodsId > 0 and !empty($goodsCode)) {
            $GoodsInfo  = $this->getDbshopTable('ApiSetGoodsTable')->infoApiGoods(array('dbapi_goods_code'=>$goodsCode, 'goods_id'=>$goodsId));
            if(!empty($GoodsInfo)) exit(json_encode(array('state'=>'have')));

            $GoodsArray = array();
            $GoodsArray['dbapi_goods_code']  = $goodsCode;
            $GoodsArray['goods_id']          = $goodsId;
            $GoodsArray['dbapi_goods_sort']  = 255;
            $this->getDbshopTable('ApiSetGoodsTable')->addApiGoods($GoodsArray);

            exit(json_encode(array('state'=>'true')));
        }
        exit(json_encode(array('state'=>'false')));
    }
    /**
     * 更新api商品信息
     */
    public function updateApiGoodsAction()
    {
        $dbapiGoodsId   = intval($this->request->getPost('dbapi_goods_id'));
        $dbapiGoodsSort = intval($this->request->getPost('dbapi_goods_sort'));
        if($dbapiGoodsId > 0 and $dbapiGoodsSort > 0) {
            if($this->getDbshopTable('ApiSetGoodsTable')->updateApiGoods(array('dbapi_goods_sort'=>$dbapiGoodsSort), array('dbapi_goods_id'=>$dbapiGoodsId))) {
                exit('true');
            }
        }
        exit('false');
    }
    /**
     * 删除api商品信息
     */
    public function delApiGoodsAction()
    {
        $dbapiGoodsId   = intval($this->request->getPost('dbapi_goods_id'));
        $goodsCode      = trim($this->request->getPost('goods_code'));
        if($dbapiGoodsId > 0 and !empty($goodsCode)) {
            if($this->getDbshopTable('ApiSetGoodsTable')->delApiGoods(array('dbapi_goods_id'=>$dbapiGoodsId))) {
                exit('true');
            }
        }
        exit('false');
    }
    /**
     * 清除商品
     * @return array
     */
    public function goodsClearAction()
    {
        $clearState= $this->getDbshopLang()->translate('API商品清除失败！');
        $goodsCode = trim($this->request->getPost('goods_code'));
        if(!empty($goodsCode)) {
            if($this->getDbshopTable('ApiSetGoodsTable')->delApiGoods(array('dbapi_goods_code'=>$goodsCode))) {
                exit('true');
            }
        }

        exit($clearState);
    }
    /**
     * 文章设置列表
     * @return array
     */
    public function cmsIndexAction()
    {
        $array = array();

        $array['cms'] = $this->appIni('cms');

        $cmsGroup = $this->getDbshopTable('ApiSetCmsTable')->listApiCmsGroup(array());
        if(is_array($cmsGroup) and !empty($cmsGroup)) {
            foreach($cmsGroup as $cmsValue) {
                $array['cms_group'][$cmsValue['dbapi_cms_code']] = $cmsValue;
            }
        }

        return $array;
    }
    /**
     * 设置文章
     * @return array
     */
    public function cmsEditAction()
    {
        $code = $this->request->getQuery('code');
        if(empty($code)) return $this->redirect()->toRoute('dbapi/default', array('action'=>'cmsIndex'));

        $array['cms'] = $this->appIni('cms', $code);

        $array['cms_list'] = $this->getDbshopTable('ApiSetCmsTable')->listApiCms(array('dbapi_cms_code'=>$code));

        return $array;
    }
    /**
     * 更新文章
     */
    public function updateApiCmsAction()
    {
        $dbapiCmsId   = intval($this->request->getPost('dbapi_cms_id'));
        $dbapiCmsSort = intval($this->request->getPost('dbapi_cms_sort'));
        if($dbapiCmsId > 0 and $dbapiCmsSort > 0) {
            if($this->getDbshopTable('ApiSetCmsTable')->updateApiCms(array('dbapi_cms_sort'=>$dbapiCmsSort), array('dbapi_cms_id'=>$dbapiCmsId))) {
                exit('true');
            }
        }
        exit('false');
    }
    /**
     * 删除文章
     */
    public function delApiCmsAction()
    {
        $dbapicmsId   = intval($this->request->getPost('dbapi_cms_id'));
        if($dbapicmsId > 0) {
            if($this->getDbshopTable('ApiSetCmsTable')->delApiCms(array('dbapi_cms_id'=>$dbapicmsId))) {
                exit('true');
            }
        }
        exit('false');
    }
    /**
     * 添加文章
     */
    public function addApiCmsAction()
    {
        $cmsCode = trim($this->request->getPost('cms_code'));
        $cmsId   = intval($this->request->getPost('cms_id'));
        if($cmsId > 0 and !empty($cmsCode)) {
            $cmsInfo  = $this->getDbshopTable('ApiSetCmsTable')->infoApiCms(array('dbapi_cms_code'=>$cmsCode, 'cms_id'=>$cmsId));
            if(!empty($cmsInfo)) exit(json_encode(array('state'=>'have')));

            $cmsArray = array();
            $cmsArray['dbapi_cms_code']  = $cmsCode;
            $cmsArray['cms_id']          = $cmsId;
            $cmsArray['dbapi_cms_sort']  = 255;
            $this->getDbshopTable('ApiSetCmsTable')->addApiCms($cmsArray);

            exit(json_encode(array('state'=>'true')));
        }
        exit(json_encode(array('state'=>'false')));
    }
    /**
     * 清除文章
     * @return array
     */
    public function cmsClearAction()
    {
        $clearState= $this->getDbshopLang()->translate('API文章清除失败！');
        $cmsCode = trim($this->request->getPost('code'));
        if(!empty($cmsCode)) {
            if($this->getDbshopTable('ApiSetCmsTable')->delApiCms(array('dbapi_cms_code'=>$cmsCode))) {
                exit('true');
            }
        }

        exit($clearState);
    }
    /**
     * 自动完成检索
     */
    public function autocompleteCmsSearchAction()
    {
        $keyword = trim($this->request->getQuery('q'));

        $cmsList = '';
        if(!empty($keyword)) {
            $cmsArray = $this->getDbshopTable('SingleArticleTable')->listSingleArticle(array('e.single_article_title like \'%'.$keyword.'%\''), array('dbshop_single_article.single_article_id DESC'), 20);
            if(is_array($cmsArray) and !empty($cmsArray)) {
                foreach ($cmsArray as $cmsValue) {
                    $cmsList .= $cmsValue['single_article_title'].'|'.$cmsValue['single_article_id']."\n";
                }
            }
        }
        exit($cmsList);
    }
    /**
     * 获取ini内指定的信息
     * @param string $type
     * @param string $code
     * @return array
     */
    private function appIni($type='ad', $code='')
    {
        $iniFile = DBSHOP_PATH . '/module/Extendapp/Dbapi/ini/app.ini';
        $iniRead = new Ini();
        $appIni  = $iniRead->fromFile($iniFile);

        return isset($appIni[$type]) ? (!empty($code) ? $appIni[$type][$code] : $appIni[$type]) : array();
    }
    /**
     * 数据表调用
     * @param string $tableName
     * @return multitype:
     */
    private function getDbshopTable ($tableName)
    {
        if (empty($this->dbTables[$tableName])) {
            $this->dbTables[$tableName] = $this->getServiceLocator()->get($tableName);
        }
        return $this->dbTables[$tableName];
    }
}
